package com.git.xxx.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Component
@Slf4j
public class DynamicFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation filterInvocation = (FilterInvocation) object;
        String requestMethod = filterInvocation.getRequest().getMethod();
        String requestUrl = filterInvocation.getRequest().getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //todo 这样写感觉好low,与ResourceServerConfig的83行耦合
        if(antPathMatcher.match("/api/**",requestUrl)){
            //todo 通过URL查询数据库或redis或者远程访问以获取角色列表,这里直接写硬代码
            log.info("通过Method["+requestMethod+"],URI["+requestUrl+"]获取其对应的权限[ROLE_PROJECT_ADMIN]");
            Set<ConfigAttribute> set = new HashSet<>();
            SecurityConfig securityConfig = new SecurityConfig("ROLE_PROJECT_ADMIN");
            set.add(securityConfig);
            return set;
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
